package tech.aister.controller.manager;

import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import tech.aister.pojo.Book;
import tech.aister.pojo.Msg;
import tech.aister.service.BookService;
import tech.aister.service.CategoryService;
import tech.aister.utils.CommonUtils;
import tech.aister.utils.FileUtil;

import javax.servlet.http.HttpSession;
import java.io.File;

@Controller//@Controller表示在tomcat启动的时候，把这个类作为一个控制器加载到Spring的Bean工厂
@RequestMapping("/manager")
//，RequestMapping表示类中的所有响应请求的方法都是以该地址作为父路径
public class BookController {

	private final int pageSize=15;

	@Autowired
	private BookService service;
	@Autowired
	private CategoryService categoryService;

	@RequestMapping("/getAllBook")
	//@RequestParam主要用于将请求参数区域（url传参数）的数据映射到控制层方法的参数上
	public String getAllBook(@RequestParam(defaultValue="1")int pageNum, Model model){
		//后端利用model.addAttribute()传递数据，前端利用th标签接收，用于前后端传递数据，
		// 传递的参数为list时，前端利用表格或其他接收，为字符串时，同文档。
		PageInfo<Book> pageInfo=service.getAllBook(pageNum,pageSize);
		model.addAttribute("pageInfo",pageInfo);
		model.addAttribute("url","getAllBook");
		return "manager/listBook";
	}

	@RequestMapping("/forUpdateBook")
	//更新图书
	public String forUpdateBook(@RequestParam String id, Model model){
		model.addAttribute("book",service.findBookById(id));
		model.addAttribute("categories",categoryService.getAllCategory());
		return "manager/editBook";
	}

	@RequestMapping("/getAllBookByCategory")
	public String getAllBookByCategory(@RequestParam String category_id, @RequestParam(defaultValue="1")int pageNum, Model model){
		PageInfo<Book> pageInfo=service.getAllBookByCategory(category_id, pageNum,pageSize);
		model.addAttribute("pageInfo",pageInfo);
		model.addAttribute("url","getAllBookByCategory");
		return "manager/listBook";
	}

	@RequestMapping("/queryBook")
	public String queryBook(Book book, @RequestParam(defaultValue="1")int pageNum, Model model){
		PageInfo<Book> pageInfo=service.queryBook(book, pageNum,pageSize);
		model.addAttribute("pageInfo",pageInfo);
		model.addAttribute("url","queryBook");
		model.addAttribute("query_name",book.getName());
		return "manager/listBook";
	}
	@RequestMapping("/findBookById")
	//通过图书的id找图书
	public String findBookById(@RequestParam String id, Model model) {
		Book book=service.findBookById(id);
		model.addAttribute("book",book);
		model.addAttribute("url","findBookById");
		return "manager/editBook";
	}

	@RequestMapping("/addBook")
	//添加图书
	public String addBook(Book book, @RequestParam("file") MultipartFile file, HttpSession session, Model model) {
		  String filename=doUpload(file,session);
		  book.setImage(filename);
		  service.addBook(book);
		  model.addAttribute("msg","添加成功");
		  return "manager/right";
	}

	private String doUpload(MultipartFile file, HttpSession session) {
		    String filename = file.getOriginalFilename();
            String suffixName=filename.substring(filename.lastIndexOf("."));
	        String filePath = session.getServletContext().getRealPath("upload/images/");
	        String newName= CommonUtils.uuid()+suffixName;
	        try {
	            FileUtil.uploadFile(file.getBytes(), filePath, newName);
	        } catch (Exception e) {
	        	e.printStackTrace();
	        }
	        return newName;
	}



	@RequestMapping("/deleteBook")
	@ResponseBody
	//删除图书
	// HttpSession是一个接口。
	//        当flag为true时：
	//                    先查看请求当中是否有sessionId,如果没有，
	//                则创建一个session对象。如果有，则依据sessionId
	//                查找对应的session对象，如果找到了，则返回该
	//                对象，如果找不到，创建一个新的session对象。
	//        当flag为false时:
	//                    先查找请求当中是否有sessionId，如果没有，
	//                返回null。如果有，则依据sessionId查找对应的session
	//                对象，如果找到了，则返回该对象，如果找不到，返回
	//                null。
	public Msg deleteBook(HttpSession session, @RequestParam String id){
		Book book=service.findBookById(id);
		try {
			service.deleteBook(id);
			File file=new File(session.getServletContext().getRealPath("upload/images/")+book.getImage());
			file.delete();
			return new Msg(1,"删除成功");
		}catch(Exception e) {
			e.printStackTrace();
			return new Msg(0,"删除失败");
		}
	}

	@RequestMapping("/updateBook")
	//修改图书的一些参数
	public String updateBook(Book book, @RequestParam("file") MultipartFile file, HttpSession session, Model model) {
		String uploadname=file.getOriginalFilename();
		if(uploadname!=null&&!uploadname.trim().isEmpty()) {
		    String newName=doUpload(file, session);
			File oldImage=new File(session.getServletContext().getRealPath("upload/images/")+book.getImage());
			oldImage.delete();
			book.setImage(newName);
		}  else {
			book.setImage(book.getImage());
		}
		service.updateBook(book);
		model.addAttribute("msg","修改成功");
		return "/manager/right";
	}

}
